---
category: DOM
created: '2020-04-19'
title: Insert an element before other one
updated: '2021-10-13'
---

**JavaScript version**

```js insertBefore.js
const insertBefore = (ele, anotherEle) => anotherEle.parentNode.insertBefore(ele, anotherEle);

// Or
const insertBefore = (ele, anotherEle) => anotherEle.insertAdjacentElement('beforebegin', ele);
```

**TypeScript version**

```ts insertBefore.ts
const insertBefore = (ele: Element, anotherEle: Element): Element | null =>
    anotherEle.parentNode ? anotherEle.parentNode.insertBefore(ele, anotherEle) : null;

// Or
const insertBefore = (ele: Element, anotherEle: Element) => anotherEle.insertAdjacentElement('beforebegin', ele);
```
